package com.system.elastic.canal;

import com.alibaba.fastjson.JSON;
import com.system.elastic.domain.Goods;
import com.system.elastic.feign.SkuFeign;
import com.system.elastic.good.SkuInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

@Component
@CanalTable(value = "goods")
public class GoodHandler implements EntryHandler<Goods> {


    @Autowired
    private SkuFeign skuInfoFeign;
    /***
     * 增加数据
     * @param sku
     */
    @Override
    public void insert(Goods sku) {
        System.out.println("===========insert:"+sku);
        //将Sku转换成SkuInfo
        SkuInfo skuInfo = JSON.parseObject(JSON.toJSONString(sku) ,SkuInfo.class);
        //同步索引
        skuInfoFeign.modify("1",skuInfo);
    }

    /***
     * 修改数据
     * @param before
     * @param after
     */
    @Override
    public void update(Goods before, Goods after) {
        System.out.println("===========update-after:"+JSON.toJSONString(after));
        String type="2";
        //将Sku转换成SkuInfo
        SkuInfo skuInfo = JSON.parseObject( JSON.toJSONString(after) ,SkuInfo.class);
        if(skuInfo.getStatus()==1 || after.getSeckillNum()<=0){
            //商品变成了普通商品,或者商品库存为0，则需要删除索引数据
            type="3";
        }
        //同步索引
        skuInfoFeign.modify(type,skuInfo);

    }

    /***
     * 删除数据
     * @param sku
     */
    @Override
    public void delete(Goods sku) {
        System.out.println("===========delete:"+sku);
    }
}
